package com.wzh.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.apiCommon.model.entity.UserInterfaceInfo;
import com.wzh.springbootinit.common.ErrorCode;
import com.wzh.springbootinit.exception.BusinessException;
import com.wzh.springbootinit.mapper.UserInterfaceInfoMapper;
import com.wzh.springbootinit.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

/**
* @author Admin
* @description 针对表【user_interface_info(用户接口调用关系)】的数据库操作Service实现
* @createDate 2023-04-09 20:14:25
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo> implements UserInterfaceInfoService {

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean b) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建时，所有参数必须非空
        if (b) {
            if (userInterfaceInfo.getInterfaceInfoId()<0||userInterfaceInfo.getUserId()<0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或者用戶不存在");
            }
        }
        if (userInterfaceInfo.getLeftNum()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"剩余次数不能小于0");
        }

    }


    /**
     * 调用接口统计
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId<0||userId<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId",interfaceInfoId) ;
        updateWrapper.eq("userId",userId);
        updateWrapper.gt("leftNum",0);
        updateWrapper.setSql("leftNum=leftNum-1,totalNum=totalNum+1");
        boolean update = this.update(updateWrapper);
        return update;
    }


}
